package xworker.swt.data.listeners;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Control;
import org.xmeta.ActionContext;
import org.xmeta.Thing;
import xworker.dataObject.DataObject;
import xworker.dataObject.DataObjectList;
import xworker.dataObject.DataObjectListListener;

import java.util.Collection;

public class SwtDataObjectListListener implements DataObjectListListener {
    Thing thing;
    ActionContext actionContext;

    public SwtDataObjectListListener(Thing thing, ActionContext actionContext){
        this.thing = thing;
        this.actionContext = actionContext;
    }

    @Override
    public void onReconfig(DataObjectList list) {
        thing.doAction("onReconfig", actionContext, "list", list, "listener", this);
    }

    @Override
    public void onLoaded(DataObjectList list) {
        thing.doAction("onLoaded", actionContext, "list", list, "listener", this);
    }

    @Override
    public void onAdded(DataObjectList list, DataObject dataObject) {
        thing.doAction("onAdded", actionContext, "list", list, "dataObject", dataObject, "listener", this, "index", -1);
    }

    @Override
    public void onAdded(DataObjectList list, int index, DataObject dataObject) {
        thing.doAction("onAdded", actionContext, "list", list, "index", index, "dataObject", dataObject, "listener", this);
    }

    @Override
    public void onAddedAll(DataObjectList list, int index, Collection<? extends DataObject> c) {
        thing.doAction("onAddedAll", actionContext, "list", list, "index", index, "c", c, "listener", this);
    }

    @Override
    public void onRemoved(DataObjectList list, int index, DataObject dataObject) {
        thing.doAction("onRemoved", actionContext, "list", list, "dataObject", dataObject, "index", index, "listener", this);
    }

    @Override
    public void onSeted(DataObjectList list, int index, DataObject newDataObject, DataObject oldDataObject) {
        thing.doAction("onSeted", actionContext, "list", list, "newDataObject", newDataObject, "oldDataObject", oldDataObject, "listener", this);
    }

    public static SwtDataObjectListListener create(ActionContext actionContext){
        Thing self = actionContext.getObject("self");

        Control control = self.doAction("getControl", actionContext);
        if(control == null){
            if(actionContext.get("parent") instanceof Control){
                control = actionContext.getObject("parent");
            }
        }
        DataObjectList dataObjectList = self.doAction("getDataObjectList", actionContext);

        SwtDataObjectListListener listener = new SwtDataObjectListListener(self, actionContext);
        dataObjectList.addListener(listener);

        if(control != null && !control.isDisposed()){
            control.addListener(SWT.Dispose, event -> dataObjectList.removeListener(listener));
        }

        actionContext.g().put(self.getMetadata().getName(), listener);

        return listener;
    }
}
